package cn.edu.zjicm.wordsnet_d.download;

/* 在设置学习计划界面(SettingPlanActivity)被调用 */

import java.util.Iterator;
import java.util.Set;

import android.content.Context;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.VoicePack;
import cn.edu.zjicm.wordsnet_d.datapersistent.FileManager;
import cn.edu.zjicm.wordsnet_d.view.MyDialog;

public class DownloadManager {

	private Context context;
	private Handler handler;
	private boolean downloadForOneWord = false;
	private OneWord word;

	public static int allZipSize = 0; // 所有需要下载的语音包大小
	public static int allHasDownloadSize = 0; // 已经下载的语言包大小
	private StringBuilder downloadZipName = null; // 正在下载的语言包名称

	public DownloadManager(Context context, Handler handler, boolean downloadForOneWord, OneWord word) {
		this.context = context;
		this.handler = handler;
		this.downloadForOneWord = downloadForOneWord;
		this.word = word;
		new JudgeNetwork(context);
		reset();
	}

	public DownloadManager(Context context, Handler handler) {
		this.context = context;
		this.handler = handler;
		new JudgeNetwork(context);
		reset();
	}

	private void reset() {
		allZipSize = 0;
		allHasDownloadSize = 0;
		downloadZipName = null;
	}

	private MyDialog showAskToDownloadDialog;
	private MyDialog mDownloadingWindow;
	private ProgressBar mDownloadProgressBar;
	private TextView mDownloadingProgressText;
	private TextView mDownloadingHintText;
	private Button mHideButton;

	public void showAskDownloadWindow() {
		initDownloadList();
		if (showAskToDownloadDialog == null) {
			View view = View.inflate(context, R.layout.window_ask_downlaod, null);
			TextView remind1 = (TextView) view.findViewById(R.id.downloadRemind1);
			TextView remind2 = (TextView) view.findViewById(R.id.downloadRemind2);
			showAskToDownloadDialog = new MyDialog(context, view, R.style.mydialog, false);
			showAskToDownloadDialog.setCanceledOnTouchOutside(false);

			if (JudgeNetwork.getInstance(context).isWifiConnected()) {// 如果是wifi状态，直接下载
				remind1.setText("当前网络连接正常");
				remind2.setText("点击确定开始下载");
			} else if (JudgeNetwork.getInstance(context).isMobileConnected()) {// 如果使用的是流量，提醒一下
				remind1.setText("您的手机正在使用非wifi网络，可能会耗费较多的流量");
				remind2.setText("确定继续下载吗？");
			} else {// 提醒用户网络无法连接
				remind1.setText("当前网络连接不正常，无法下载语音包");
				remind2.setText("请打开网络连接后，在设置页面下载");
			}
			TextView downloadFileSizeRemind = (TextView) view.findViewById(R.id.downloadFileSizeRemind);
			downloadFileSizeRemind.setText("语音包下载 (共" + String.format("%.1f", voicePackSize) + "MB)");
			Button confirmButton = (Button) view.findViewById(R.id.download_read_confirm_button);
			Button cancleButton = (Button) view.findViewById(R.id.download_read_cancle_button);
			if (!JudgeNetwork.getInstance(context).isWifiConnected() && !JudgeNetwork.getInstance(context).isMobileConnected()) {
//				confirmButton.setVisibility(View.GONE);
//				cancleButton.setVisibility(View.GONE);
				view.findViewById(R.id.two_btn_layout).setVisibility(View.GONE);
				Button OKBtn = (Button) view.findViewById(R.id.got_it);
				OKBtn.setVisibility(View.VISIBLE);
				OKBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						showAskToDownloadDialog.dismiss();
						showAskToDownloadDialog = null;
						handler.sendMessage(handler.obtainMessage(2));
					}
				});

			} else {
				confirmButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						showAskToDownloadDialog.dismiss();
						showDownloadingWindow();
						showAskToDownloadDialog = null;
						startDownload();
					}
				});
			}
			cancleButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					showAskToDownloadDialog.dismiss();
					showAskToDownloadDialog = null;
					handler.sendMessage(handler.obtainMessage(2));
				}
			});
			
		}
		showAskToDownloadDialog.show();
	}

	public View showDownloadingWindow() {
		View view = null;
		if (mDownloadingWindow == null) {
			view = View.inflate(context, R.layout.window_downlaoding, null);
			mDownloadingWindow = new MyDialog(context, view, R.style.mydialog, false);
			mDownloadingWindow.setCanceledOnTouchOutside(false);

			LinearLayout downloadingWindow = (LinearLayout) view.findViewById(R.id.downloading_window);
			downloadingWindow.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					return false;
				}
			});
			mHideButton = (Button) view.findViewById(R.id.downloading_hide_button);
			mDownloadProgressBar = (ProgressBar) view.findViewById(R.id.downloading_progress_bar);
			mDownloadProgressBar.setMax(MAX_PROGRESS_LEVEL);
			mDownloadingProgressText = (TextView) view.findViewById(R.id.downloading_progress_text);
			mDownloadingHintText = (TextView) view.findViewById(R.id.downloading_hint_tv);
			mHideButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					handler.sendMessage(handler.obtainMessage(2));
					mDownloadingWindow.dismiss();
				}
			});
		}
		mDownloadingWindow.show();
		return view;
	}

	double voicePackSize; // 需要下载的语音包的大小
	Set<String> downloadPackList; // 需要下载的语音包名列表
	int downloadPackCount; // 需要下载的语音包的个数

	// String downloadPack; //正在下载的语音包名

	// 初始化下载语音包列表
	void initDownloadList() {
		if (!downloadForOneWord) {
			downloadPackList = FileManager.getDownloadVoicePackList(false, true, context);
		} else {
			downloadPackList = FileManager.getDownloadVoicePackList(word, context);
		}

		voicePackSize = 0;
		String packName;
		downloadZipName = new StringBuilder();
		Iterator<String> it = downloadPackList.iterator();
		int i = 0;
		while (it.hasNext()) {
			packName = it.next();
			voicePackSize += VoicePack.getVoicePackSize(packName);
			allZipSize += VoicePack.getVoicePackRealSize(packName);

			if (i == 0) {
				downloadZipName.append(packName);
			}
			i++;
		}

		downloadPackCount = downloadPackList.size();
		if (downloadPackCount > 1) {
			downloadZipName.append("等").append(downloadPackCount).append("个语音包");
		}

	}

	// 依次下载语音包列表，如全部下载完则跳转
	void startDownload() {
		Iterator<String> it = downloadPackList.iterator();
		while (it.hasNext()) {
			DownloadVoicePackManager downloadManager = DownloadVoicePackManager.getInstance(context, it.next(), mRefreshUiHandler, false);
			downloadManager.startToDownload();

		}
	}

	private static final int MAX_PROGRESS_LEVEL = 100;

	private Handler mRefreshUiHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// Log.d("mRefreshUiHandler", "handleMessage");
			// if (!((Activity) context).isFinishing()) {
			String packName = null;
			switch (msg.what) {
			case DownloadVoicePackManager.UPDATE:
				if (mDownloadProgressBar != null && mDownloadingProgressText != null && mDownloadingWindow.isShowing()) {
					String str[] = ((String) msg.obj).split(":");
					int progress = msg.arg1;
					mDownloadProgressBar.setProgress(progress);
					mDownloadingProgressText.setText(str[0]);
					String name;
					if (downloadZipName != null && downloadZipName.length() > 0) {
						name = downloadZipName.toString();
					} else {
						name = str[1];
					}
					mDownloadingHintText.setText("正在下载" + name + "... \n语音包下载可能需要较长时间，请稍候...");
				}
				break;
			case DownloadVoicePackManager.SUCCESS:
				packName = (String) msg.obj;
				Toast.makeText(context, packName + "下载成功", Toast.LENGTH_SHORT).show();
				// startDownload();
				downloadPackCount--;
				if (downloadForOneWord || downloadPackCount == 0)
					handler.sendMessage(handler.obtainMessage(2));
				if (downloadPackCount == 0) {
					mDownloadingWindow.dismiss();
				}
				break;
			case DownloadVoicePackManager.FAIL:
				packName = (String) msg.obj;
				Toast.makeText(context, packName + "下载失败，请确保网络连接正常，并保证sd卡有足够的可用空间！", Toast.LENGTH_SHORT).show();
				// startDownload();
				downloadPackCount--;
				if (downloadPackCount == 0) {
					handler.sendMessage(handler.obtainMessage(2));
					mDownloadingWindow.dismiss();
				}
				break;
			}
			// }
		};
	};
}
